using UnityEngine;
using System.Collections;
using DanielSig;
using DanielSig.UnityExtensions;

[RequireComponent(typeof(CapsuleCollider))]
public class ProjectileController : MonoBehaviour
{
	public float Speed;
	public float Damage;
	public Color FlashColor;
	public LayerMask CollisionMask;
	public GameObject Shooter;
	
	void Awake()
	{
		GameCore.Register(ProjectileUpdate);
		StartCoroutine(Fire());
	}
	void OnDestroy()
	{
		GameCore.Unregister(ProjectileUpdate);
	}
	IEnumerator Fire()
	{
		enabled = false;
		yield return new WaitForFixedUpdate();
		enabled = true;
	}
	
	void ProjectileUpdate ()
	{
		CapsuleCollider cap = collider as CapsuleCollider;
		Vector3 dir = transform.forward;
		Vector3 step = dir * Speed * Time.fixedDeltaTime;
		Vector3 start = -dir * cap.height / 2;
		float length = Speed * Time.fixedDeltaTime + cap.height;
		float radius = cap.radius;
		
		for(int i = 0; i < GameCore.IterationsPerFrame; i++)
		{
			transform.Translate(step, Space.World);
			
			RaycastHit hit;
			if(Physics.SphereCast(transform.position + start - step, radius, dir, out hit, length, CollisionMask.value))
			{
				
				if((CollisionMask.value & (1 << hit.transform.gameObject.layer)) > 0)
				{
					hit.collider.SendMessage("ProjectileImpact", Damage, SendMessageOptions.DontRequireReceiver);
					hit.collider.SendMessage("FlashScreen", FlashColor, SendMessageOptions.DontRequireReceiver);
					if(Shooter)
						Shooter.SendMessage("ProjectileHit", hit.collider.gameObject);
					Destroy(gameObject, 0.05F);
					Destroy(this);
					return;
				}
			}
		}
	}
}

